package com.smf.lsc.core.exception;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Random;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smf.lsc.core.respones.Result;
import com.smf.lsc.core.respones.ResultUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局异常拦截处理
 * Created on 2021/11/19.
 *
 * @author ln
 * @since 1.0
 */
@ControllerAdvice
@Slf4j
public class ExceptionHandlerAdvice {
	
	private final int ERROR_CODE_MAX=99999;
	private final int ERROR_CODE_MIN=90000;
	
	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public Result exceptionHandler(Exception ex) {
		String errorMessage=getExceptionInfo(ex);
		//判断异常是否是自定义的异常
		if (ex instanceof BaseException) {  
			log.error(errorMessage);
            return ResultUtil.errorResult(((BaseException) ex).getCode(), ex.getMessage(), null);
        }else {
        	Random ra = new Random();
    		int errorCode = ra.nextInt(ERROR_CODE_MAX) % (ERROR_CODE_MAX - ERROR_CODE_MIN + 1) + ERROR_CODE_MIN;
    		log.error("异常流水号: "+errorCode+" "+errorMessage);
    		return ResultUtil.errorResult(errorCode, ex.toString(),null);
        }
	}
	
	private String getExceptionInfo(Exception ex) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream printStream = new PrintStream(out);
        ex.printStackTrace(printStream);
        String rs = new String(out.toByteArray());
        try {
            printStream.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;
    }
}